package com.yun.util.yun.utils.IP;

/**
 *
 * @Description IPV4计算
 */
public final class IPNetWork {
    private IPAddress addressFirst;
    private IPAddress addressLast;
    /**
     * 传入IP
     * 如果IP不带掩码，默认为全量(/32)
     * @param ip
     */
    public IPNetWork fromString(String ip) throws Exception
    {
        if("".equals(ip)||isIp(ip))
        {
            throw new Exception("IP空，无法计算");
        }
        String[] ips=ip.split("/");
        String networkAddressString = ips[0];
        if(isIp(networkAddressString))
        {
            throw new Exception("IP格式不合法，无法计算");
        }
        this.setFirstAddress(networkAddressString);
        //32位掩码为全量掩码
        if(ips.length<=1)
        {
            this.setLastAddress(networkAddressString);
            return this;
        }
        int prefixLength  = Integer.parseInt(ips[1]);
        this.addressLast=new IPAddress(networkAddressString,prefixLength);
        return this;
    }

    public boolean isIp(String text) {
        String regex ="^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
                +"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                +"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                +"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)"
                +":([0-9]|[1-9]\\d{1,3}|[1-5]\\d{4}|6[0-5]{2}[0-3][0-5])$";
        // 判断ip地址是否与正则表达式匹配
        if (text.matches(regex))
        {
            return true;
        }

        return false;
    }

    private void setFLAddress(String ipF,String ipL)
    {
        setFirstAddress(ipF);
        setLastAddress(ipL);
    }
    private void setFirstAddress(String ip) { this.addressFirst=new IPAddress(ip); }
    private void setLastAddress(String ip)
    {
        this.addressLast=new IPAddress(ip);
    }

    public String getAddressFirst()
    {
        return this.addressFirst.getIp();
    }
    public String getAddressLast()
    {
        return this.addressLast.getIp();
    }

    public static void main(String[] args) throws Exception {
        IPNetWork ipANetWork = new IPNetWork().fromString("192.168.1.5/16");
        System.out.println(ipANetWork.getAddressFirst());
        System.out.println(ipANetWork.getAddressLast());
        //IPv6Address.fromString("2409:8087::01");

    }
}